LeetCode JS Easy 2704. To Be Or Not To Be


Posted by Lucy on 2023-06-10

這是30 Days of JavaScript中的題型
Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.

toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error "Not Equal".
notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error "Equal".
最常見寫法應該就兩個function

var expect = function(val) {
    const toBe=(eqalVal)=>{if(val===eqalVal)return true
                throw new Error("Not Equal")
    }    
    const notToBe=(eqalVal)=>{if(val!==eqalVal)return true
                throw new Error("Equal")
    }
      return {
          toBe:toBe,
          notToBe:notToBe,
      }
};

不過不知道為什麼我就很想寫共用function,下面這段是第一次寫的

var expect = function(val) {
    const fn=(eqalVal,isToBe)=>{
            const isEqal=val===eqalVal
            if(isToBe){
                if(isEqal)return true
                throw new Error("Not Equal")
            }else{
                if(isEqal)throw new Error("Equal")
                return true
            }
        }
      return {
          toBe:(eqalVal)=>fn(eqalVal,true),
          notToBe:(eqalVal)=>fn(eqalVal,false),
      }
};

#leetcode Js







Related Posts

Day02_Origami學習筆記

Day02_Origami學習筆記

day_04: 我不會物件導向

day_04: 我不會物件導向

JavaScript 網頁事件處理 2

JavaScript 網頁事件處理 2


Comments